<?php

// $Id$

require_once($WSC->get_site_inc_dir().'modules/admin_panel/site_admin_web_page_wed_ua.class.php');
require_once($WSC->get_site_inc_dir().'modules/tree_menu_ml/tree_menu_ml_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tree_menu_ml/tree_menu_item_ml_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tree_menu_ml/tree_menu_ml_label_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/language_detector_advanced/vl_language_dbc.class.php');


class Menu_Item_Export_WP extends Site_Admin_Web_Page_WED_UA {
	public function init() {
		parent::init();

		$v = $this->create_view();
		$this->add_view($v);

		$item_event = new Web_Event_Simple_Int('item', Tangra_Parameter_Method::GET, 'item');
		$prefix_event = new Web_Event_Simple('prefix', Tangra_Parameter_Method::GET, 'prefix');

		$comp = new Web_Event_Composite('export');
		$comp->add_wes($item_event);
		$comp->add_wes($prefix_event);
		$this->wed->add_wed_event_action_pair($comp, 'export_event');

	}


	protected function export_event($params) {
		$item = new Tree_Menu_Item_ML_DBC($params['prefix'].'menu', 1);
		$dbc = $this->get_dbc();

		$lang_ids = array_flip(VL_Language_DBC::load_all_languages_ids($dbc));
		$this->export('langs', $lang_ids);

		if ($params['item'] != 0) {
			if ($item->load_by_id_full($dbc, $params['item'])) {
				$items = $this->get_items(array($item));
				$items_arr = $this->prepare_items_arr($items);

				$this->export('items', $items_arr);

				$view = $this->get_view('default');

			} else {
				$view = $this->get_view('not_exist');

			}
		} else {
			$menu = new Tree_Menu_ML_DBC($params['prefix'].'menu', 1);
			$menu->load_menu($dbc, true);

			$items_raw = $menu->get_items();
			$items = $this->get_items($items_raw);
			$items_arr = $this->prepare_items_arr($items);

			$this->export('items', $items_arr);

			$view = $this->get_view('default');

		}


		return $view;
	}


	protected function default_event() {
		throw new Tangra_User_Exception('Unexpected or missing parameters.');
	}


	private function get_items($items) {
		$ret = array();

		foreach($items as $item) {

			$ret[] = $item;

			if ($item->get_subitems()) {
				$tmp = $this->get_items($item->get_subitems());

				$ret = array_merge($ret, $tmp);
			}
		}


		return $ret;
	}


	private function prepare_items_arr($items) {
		$c = 0;
		$ret = array();

		$dbc = $this->get_dbc();

		foreach($items as $item) {
			$ret[$c]['item'] = $item;

			$parent_id = $item->get_parent();
			if ($parent_id) {
				$tmp = new Tree_Menu_Item_DBC($item->get_table());
				$tmp->load_by_id($dbc, $parent_id);
				$ret[$c]['parenthid'] = $tmp->get_hid();
			} else {
				$ret[$c]['parenthid'] = '';
			}
			$c++;
		}

		return $ret;
	}
}


